<?php

namespace app\admin\controller;

/**
 * Auth权限管理-用户组管理控制器
 * Class Group
 * @package app\admin\controller
 */
class Group extends Common
{
	private $db;

	public function __construct()
	{
		parent::__construct();
		$this->db = new \app\common\model\Group();
	}

	//列表页
	public function index()
	{
		$data = db('authgroup')->order('id desc')->paginate(8);
		return view('', compact('data'));
	}

	//添加
	public function add()
	{
		//1.调用getRules方法
		$navArr = $this->getRules();

		//2.执行添加
		if (request()->isPost()) {
			$res = $this->db->add(input('post.'));
			if ($res['valid']) {
				$this->success($res['msg'], 'index');
			} else {
				$this->error($res['msg']);
			}
		}

		//载入模板同时分配变量
		return view('', Compact('navArr'));
	}

	//处理导航条对应的所有方法
	private function getRules()
	{
		$rules = db('authrule')->select();
		$navArr = [];
		foreach ($rules as $k => $v) {
			$navArr[$v['nav']][] = $v;
		}
		return $navArr;
	}

	//编辑
	public function edit()
	{
		//获取规则
		$rules = $this->getRules();
		$this->assign('rules', $rules);

		$id = input('param.id');
		$oldData = db('authgroup')->find($id);
		$oldData['rules'] = explode(',', $oldData['rules']);
		$this->assign('oldData', $oldData);

		if (request()->isPost()) {
			$res = $this->db->edit(input('post.'));
			if ($res['valid']) {
				$this->success($res['msg'], 'index');
			} else {
				$this->error($res['msg']);
			}
		}
		return view();
	}


	//删除
	public function del()
	{
		$id = input('param.id');
		$res = \app\common\model\Group::destroy($id);
		if ($res) {
			$this->success('删除成功', 'index');
		} else {
			$this->error('删除失败');
		}
	}
}
